<template>
    <div class="addNews">
        <h2 class="tit">健康资讯编辑</h2>
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate">
            <div class="pert">
				<p class="title">基本信息</p>
                <Row class="box">
                    <Col span="16">
                        <!-- 新闻标题 -->
                        <div class="address">
                            <div class="left">
                                <span class="hongdian">*</span>
                                <span>新闻标题：</span>
                            </div>     
                            <FormItem class="newstit" prop="title">
                                <Input v-model.trim="formValidate.title" placeholder="输入标题30个汉字以内" :maxlength="30"/>
                            </FormItem>
                        </div>
                    </Col>  
                    <Col span="8">
                        <div class="address">
                        <!-- 副酷暑 -->
                            <div class="left">
                                <span>摘要/副标题：</span>
                            </div>       
                            <FormItem class="word" prop="synopsis">
                                <Input v-model.trim="formValidate.synopsis" placeholder="输入标题50个汉字以内" :maxlength="50"/>
                            </FormItem>
                        </div>
                    </Col>
                    <Col span="8">
                        <!-- 栏目 -->
                        <div class="address">
                            <div class="left">
                                <span>栏目：</span>
                            </div>             
                            <FormItem prop="ids">
                                <Select v-model="formValidate.ids" class="lanmu">
                                    <!-- <Option :value="1" :key="1">医院简介</Option>
                                    <Option :value="2" :key="2">医院公告</Option>
                                    <Option :value="3" :key="3">就诊指南</Option>
                                    <Option :value="4" :key="4">健康咨讯</Option>
                                    <Option :value="5" :key="5">科普</Option>
                                    <Option :value="6" :key="6">决策者说</Option> -->
                                    <Option v-for="(item,index) in categories" :value="item.id" :key="index">{{ item.name }}</Option>
                                </Select>
                            </FormItem>
                        </div>
                        <div class="address">
                            <!-- 是否发布： -->
                            <div class="left">
                                <span>是否发布：</span>
                            </div>
                            <FormItem>
                                <iSwitch v-model="formValidate.enable" size="large">
                                    <span slot="open">开启</span>
                                    <span slot="close">关闭</span>
                                </iSwitch>
                            </FormItem>
                        </div>
                        <!-- 排序： -->
                        <div class="address">              
                            <div class="left">
                                <span>优先级：</span>
                            </div>   
                            <FormItem prop="priority">
                                <input v-model.trim="formValidate.priority" class="xuhao inputnumber" @input="srInput" />
                            </FormItem>
                        </div>
                        <div class="tishi">
                            <small>（备注：只能填写数字，1代表置顶以此类推）</small>
                        </div>
                    </Col>
                    <Col span="8">
                        <div class="address">
                            <!-- 新闻来源： -->
                            <div class="left">
                                <span>新闻来源：</span>
                            </div>
                            <FormItem class="laiyuan">
                                <Input v-model.trim="formValidate.source" placeholder="输入标题20个汉字以内" :maxlength="20" />
                            </FormItem>
                        </div>
                        <Col span="18">
                            <div class="address">
                                <!-- 小图 -->
                                <div class="left">
                                    <span>列表首页：</span>
                                </div>                          
                                <FormItem >
                                    <div class="demo-upload-list" v-for="(item,index) in uploadList" :key="index">
                                        <div v-if="item.status === 'finished'">
                                            <img :src="fileBaseUrl + item.url">
                                            <div class="demo-upload-list-cover">
                                                <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                                                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                                            </div>
                                        </div>
                                        <div v-else>
                                            <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                                        </div>
                                    </div>
                                    <Upload
                                        v-show="uploadList.length ==0"
                                        ref="upload"
                                        :show-upload-list="false"
                                        :default-file-list="defaultList"
                                        :on-success="handleSuccess"
                                        :format="['jpg','jpeg','png']"
                                        :max-size="200"
                                        :on-format-error="handleFormatError"
                                        :on-exceeded-size="handleMaxSize"
                                        :before-upload="handleBeforeUpload"
                                        multiple
                                        type="drag"
                                        :action="uploadUrl"
                                        :headers="fromData"
                                        :data="uploadData"
                                        accept="image/jpeg, image/x-png, image/gif"
                                        class="picbox"
                                    >
                                        <div class="pic">
                                            <Icon type="ios-camera" size="20"></Icon>
                                        </div>
                                    </Upload>
                                    <Modal title="预览图片" v-model="visible" footer-hide>
                                        <img :src="preview" v-if="visible"  style="width: 100%">
                                    </Modal>
                                </FormItem>
                            </div>
                        </Col>
                        <Col span="6">
                            <RadioGroup v-model="formValidate.pagestyle" size="large">
                                <Radio label="1">方图</Radio>
                                <Radio label="2">长图</Radio>
                            </RadioGroup>
                        </Col>
                        <Col span="24">
                            <div class="tishi">
                                <small>（备注：图片大小不超过200kb，建议方图170*170px,长图455*200px）</small>
                            </div>
                        </Col>
                    </Col>
                    <Col span="8">
                        <div class="address">
                            <!-- 预设阅读量 -->
                            <div class="left">
                                <span>预设阅读量：</span>
                            </div>                  
                            <FormItem class="readnum">
                                <InputNumber style="width:250px" v-model.trim="formValidate.readNum" placeholder="请输入数值" :min="0" :max="99999999999"></InputNumber>
                            </FormItem>
                        </div>
                    </Col>
                </Row>
            </div>
			<div class="pert">
				<p class="title">详细内容</p>
                <Row class="box">
                    <Col span="24">             
                        <!-- 新闻内容 -->
                        <FormItem>
                            <div class="articletext">
                            <vueEditor
                                id="analysis"
                                :textHtml="info.content"
                                :urlCode="urlCode"
                                @valueHandle="afterChange"
                                :height='100'
                                style='margin:0;width: 99%;'
                                class="ql-editor"
                            ></vueEditor>
                            </div>
                        </FormItem>
                    </Col>
                </Row>  
            </div>          
        </Form>
        <div class="queding">
            <Button type="primary" @click="handleSubmit('formValidate')" :disabled='disabledSave' class="btn">
                <Icon type="ios-checkmark icon" />保存
            </Button>
            <Button @click="back" class="btn">
                <i class = "iconfont icon-butongyi icon"></i>取消
            </Button>
        </div>
    </div>
</template>

<script>
import api from "@/api/commonApi";
import vueEditor from "@/components/vueEditor";
import code from "@/configs/base.js";
export default {
    components: {
        vueEditor
    },
    data() {
        return {
            imgName: "",
            id: sessionStorage.getItem("hospitalId"),
            info: {
                content: ""
            },
            formValidate:{
                title: "",
                synopsis: "",
                ids:"1",
                priority: "",
                source: "",
                readNum: "",
                pagestyle: "",
                enable: false,
                type: '1',
            },
            ruleValidate:{
                title: [{ required: true, message: '请输入新闻标题', trigger: 'blur' }],
                synopsis: [{ required: true, message: '请输入新闻副标题', trigger: 'blur' }],
                ids: [{ required: true, message: '请选择新闻栏目', trigger: 'change', type:"number" }],
                // priority: [{ required: true, message: '请输入新闻排序', trigger: 'blur' }],
            },
            // 上传图片相关
            visible: false,
            uploadList: [],
            switch1: false,
            defaultList: [],
            uploadData: {
                json: '{"urlCode":"' + code.urlCode.patientNews + '"}'
            },
            activeUploadId: "5c2bf345-b973-4ffd-a52e-87bb9c1d2b72",
            uploadUrl: api.fileAll,
            urlCode: '{"urlCode":"' + code.urlCode.richText + '"}',
            images: "",
            source: "",
            preview: "",
            disabledSave: false,
            categories : []
        };
    },
    created() {
        let breadList = [
            { path: "/index", title: "首页" },
            {
                path: "/index/publicOperation/healthInformation/list",
                title: "健康资讯管理"
            }
        ];
        this.$emit("changeBreadList", breadList);
    },
    mounted() {
        this.uploadList = this.$refs.upload.fileList;
        let id = this.$route.query.id;
        if (id) {
            this.$axios
                .post(api.findArticleColumn, {
                    id
                })
                .then(res => {
                    if (res.data.code) {
                        let ret = res.data.object;
                        let detail = ret.dhtboOperateArticle;
                        if (detail.coverImg) {
                            this.uploadList = [];
                            this.source = detail.coverImg;
                            this.uploadList.push({
                                name: "a42bdcc1178e62b4694c830f028db5c0",
                                percentage: 100,
                                status: "finished",
                                uid: 1544263544970,
                                url: this.analysisImages(detail.coverImg)
                            });
                            // 预览图片
                            this.preview =
                                this.fileBaseUrl +
                                this.analysisImages(detail.coverImg);
                        }

                        this.info.content = res.data.object.content;
                        this.formValidate.ids = Number(ret.columnId);
                        this.formValidate.title = detail.title;
                        this.formValidate.synopsis = detail.abStract;
                        this.formValidate.priority = detail.showIndex.toString();
                        this.formValidate.content = detail.content;
                        this.formValidate.source = detail.source;
                        this.formValidate.readNum = detail.readNum;
                        this.formValidate.pagestyle = String(detail.pageStyle);
                        this.formValidate.enable = Boolean(detail.isEnable);
                    }
                });
        }
        this.$axios
                .post(api.findCategory, {
                })
                .then(res => {
                    if (res.data.code) {
                        this.categories = res.data.object;
                    }
                        
                });
    },
    methods: {
        srInput(e) {
            this.formValidate.priority=this.formValidate.priority.replace(/[^0-9]/g, '')
            if(e.target.value>9999)this.formValidate.priority=9999
        },
        handleView(name) {
            this.imgName = name;
            this.visible = true;
        },
        handleRemove(file) {
            const fileList = this.$refs.upload.fileList;
            this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
            this.uploadList.splice(fileList.indexOf(file), 1);
        },
        handleSuccess(res, file) {
            res = this.uploadFileDecrypt(res);
            file.url = res.object[0].fileName;
            this.images = JSON.stringify(res.object[0]);
            file.name = res.object[0].fileName;
            if(this.uploadList.length > 0) {
                return ""
            }
            this.uploadList.push({
                name: "a42bdcc1178e62b4694c830f028db5c0",
                percentage: 100,
                status: "finished",
                uid: 1544263544970,
                url: this.analysisImages(this.images)
            });
        },
        handleFormatError(file) {
            this.$Message.info("文件" + file.name + "上传失败");
        },
        handleMaxSize(file) {
            this.$Message.info("文件" + file.name + "过大");
        },
        handleBeforeUpload() {
            const check = this.uploadList.length < 1;
            if (!check) {
                this.$Message.info("只能上传一张图片");
            }
            return check;
        },
        // 返回
        back() {
            let query = this.$route.query;
            this.functionJS.queryNavgationTo(
                this,
                "/index/publicOperation/healthInformation/list",
                query
            );
        },
        // 保存
        handleSubmit(name) {
            console.log(this.formValidate.priority)
            this.disabledSave = true
            this.$refs[name].validate((valid) => {
                if (valid) {
                    let query = this.$route.query;
                    let images = "";
                    if (this.images && this.uploadList.length) {
                        images = this.images;
                    } else if (this.uploadList.length) {
                        images = this.source;
                    } else {
                        images = "";
                    }
                    this.info.content = this.info.content.replaceAll("<p>&nbsp;</p>","")
                    let params = {
                        //栏目
                        ids: [this.formValidate.ids],
                        //内容
                        content: this.info.content,
                        dhtboOperateArticle: {
                            //标题
                            title: this.formValidate.title.trim(),
                            // 副标题
                            abStract: this.formValidate.synopsis.trim(),
                            //图片
                            coverImg: images,
                            //排序
                            showIndex: this.formValidate.priority,
                            //来源
                            source: this.formValidate.source,
                            //预设阅读量
                            readNum: this.formValidate.readNum,
                            //图形状
                            pageStyle: Number(this.formValidate.pagestyle),
                            //显示
                            isEnable: Number(this.formValidate.enable),
                            //新闻资讯ID
                            id: this.$route.query.id,
                            type: this.formValidate.type
                        }
                    };
                    if (this.info.content == "") {
                        this.$Message.info("新闻内容不能为空");
                        this.disabledSave = false
                    } else {
                        this.$axios
                            .post(api.updateArticle, params)
                            .then(res => {
                                if (res.data.code) {
                                    this.$Message.info("修改成功");                                  
                                    this.disabledSave = false
                                    this.back()
                                } else {
                                    // setTimeout(() => {
                                        this.disabledSave = false
                                    // }, 10000);
                                    this.$Message.info("修改失败请重试");
                                }
                            })
                            .catch(err => {
                                console.log(err);
                            });
                    }
                } else {
                    this.$Message.error('请完整必款项!');
                    this.disabledSave = false
                    // setTimeout(() => {
                    //     this.disabledSave = false
                    // }, 10000);
                }
            })
            
        },
        afterChange(val) {
            this.info.content = val;
        },
        analysisImages(json) {
            try {
                json = JSON.parse(json);
                return json.fileName;
            } catch (error) {
                return "";
            }
        }
    }
};
</script>

<style scoped lang="less">
.demo-upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
}
.demo-upload-list img {
    width: 100%;
    height: 100%;
}
.demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
    display: block;
}
.demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
}
.addNews {
    width: calc(100%);
	padding: 10px 0px;
	margin: 0 auto;
	background: #fff;
	.tit {
		margin:10px 0;
		font-weight:bold;
		text-align:center;
	}
	Input {
		display: inline-block;
		width: 100%;
		border: 1px solid black;
		line-height: 30px;
		outline: none;
		background: pink;
		text-indent: 5px;
	}
	.pert {
		width: 98%;
		display: flex;
		flex-direction: column;
		margin: 10px auto;
		border: 1px solid #f0f0f0;
		box-shadow: 0 4px 3px #ebedf8;
		border-radius: 5px;
		margin-bottom: 20px;
		.title {
			font-size: 20px;
			padding-left: 15px;
			margin-bottom: 20px;
			color: #333;
			height: 40px;
			line-height: 40px;
			background: #ebedf8;         
    	}
        .address {
            display: flex;
            flex-direction: row;    
            .left {
                font-size: 14px;
                padding-top: 5px;
                span:last-child {
                    margin-right: 5px;
                }
                .hongdian {
                    color:red;
                    margin-left: -10px;
                }
            }
        }
		.box{
			padding: 0 50px;
		}
		.newstit {
			width: 86%;
		}
		.word {
			width: 75%;
		}
		.lanmu {
			width:120px;
		}
		.xuhao {
			width: 120px;
		}
		.tishi {
			margin:-20px 0 20px 0;
			color: #ff9966;
		}
		.laiyuan {
			width: 72%;
		}
		.readnum {
			width: 76%;
		}
		.picbox {
			display: inline-block;
			width:58px;
		}
		.pic {
			width: 58px;
			height:58px;
			line-height: 58px;
		}
		.xcon {
			margin:0;
			width:100%;
		}
        .inputnumber {
            width: 100%;
            background: #fff;
            border: none;
            outline: none;
            text-indent: 10px;
            line-height: 30px;
            border: 1px solid #ddd;
            border-radius: 4px;
            color: #666;
        }
        .inputnumber:focus{
            border-color:#5362e1
        }
	}
	/*保存*/
	.queding {
		width: 100%;
		text-align: center;
        .btn {
			width: 75px;
			height: 35px;
		}
	}
	.icon {
		font-size:14px;
		margin-right:5px;
	}
}
</style>